package com.os.sys.controller;

import com.os.sys.common.auth.CommonAuthService;
import com.os.sys.common.filter.AuthTarget;
import com.os.sys.common.filter.AuthType;
import com.os.sys.common.utility.*;
import com.os.sys.model.T_SYS_User;
import com.os.sys.repository.UserRepository;
import com.os.sys.service.RoleService;
import com.os.sys.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Optional;

/**
 * Created by Administrator on 2016/12/13.
 */

@RestController
@RequestMapping("/api/sys/user")
public class UserController {
    @Resource
    private PubClass pubClass;
    @Resource
    private HttpSession session;
    @Resource
    private CommonAuthService commonAuthService;
    @Resource
    private UserRepository userRepository;
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    @AuthTarget(AuthType.NONE)
    @PostMapping("/login")
    public XJsonInfo login(String acc, String pwd, String imgcode) {
        acc = userService.decryptLoginForm(acc);
        pwd = userService.decryptLoginForm(pwd);
        imgcode = userService.decryptLoginForm(imgcode);
        pwd = userService.fmtPWD(pwd);
        T_SYS_User info = userRepository.login(acc, pwd);
        if (info == null) {
            return new XJsonInfo(false, "登录失败，用户不存在或账号密码错误");
        }

        // 清空敏感数据
        info.setUserPassword("");
//        info.setLoginUserFrom(ac);
        commonAuthService.setCurrentUser(info);

        return XJsonInfo.success().setData(info);
    }

    @AuthTarget(AuthType.NONE)
    @PostMapping("/loginForAPP")
    public XJsonInfo loginForAPP(String acc, String pwd, String imgcode) {

        pwd = userService.fmtPWD(pwd);
        T_SYS_User info = userRepository.login(acc, pwd);
        if (info == null) {
            return new XJsonInfo(false, "登录失败，用户不存在或账号密码错误");
        }

        // 清空敏感数据
        info.setUserPassword("");
//        info.setLoginUserFrom(ac);
        commonAuthService.setCurrentUser(info);

        return XJsonInfo.success().setData(info);
    }

    @GetMapping("/loginOut")
    public XJsonInfo loginOut() {

        return commonAuthService.loginOut();
    }

    @GetMapping("/getList")
    public XJsonInfo getList(T_SYS_User info) {
        Pageable pageable = pubClass.createPagenation();
        Page page = userRepository.findAll((Specification<T_SYS_User>) (root, query, cb) -> {

            if (StringClass.isNotBlank(info.getUserName())) {
                query.where(cb.equal(root.<String>get("userName"), info.getUserName()));
            }

            if (StringClass.isNotBlank(info.getUserAccount())) {
                query.where(cb.equal(root.<String>get("userAccount"), info.getUserAccount()));
            }

            if (StringClass.isNotBlank(info.getUserMobile())) {
                query.where(cb.equal(root.<String>get("userMobile"), info.getUserMobile()));
            }

            return null;
        }, pageable);
        return new XJsonInfo().setPageData(page);
    }

    @GetMapping("/getModel")
    public XJsonInfo getModel(long id) {
        T_SYS_User info = userRepository.findById(id).orElse(null);
        return new XJsonInfo().setData(info);
    }

    @RequestMapping(value = "/getModelEx")
    public XJsonInfo getModelEx(long id) {
        if (id <= 0) {
            return new XJsonInfo(false);
        }
        Optional<T_SYS_User> opInfo = userRepository.findById(id);
        if (opInfo == null) {
            return new XJsonInfo(false);
        }
        T_SYS_User info = opInfo.get();
        info.setRoleIds(StringClass.join(roleService.getRolesIDsByUserId(info.getId()), ","));
        info.setRolePower(StringClass.join(roleService.getRolesPowersByUserId(info.getId()), ","));

        return new XJsonInfo().setData(info);
    }

    @PostMapping("/save")
    public XJsonInfo save(@RequestBody T_SYS_User info) {
        //Objects.requireNonNull(info);
        return userService.save(info);
    }

    @RequestMapping(value = "/updateRoles", method = RequestMethod.POST)
    public XJsonInfo updateRoles(@RequestBody T_SYS_User info) {
        if (info.getId() == null) {
            return new XJsonInfo(false, "数据不存在");
        }

        XJsonInfo re = roleService.updateUserRoles(info.getId(), info.getRoleIds());
        if (!re.getSuccess()) {
            return re;
        }
        //userZJRepository.save(info);

        return new XJsonInfo();
    }

    @AuthTarget(AuthType.NONE)
    @RequestMapping(value = "/yzm")
    public void yzm(String key) throws IOException {
        HttpServletResponse response = WebClass.getResponse();
        Captcha cap = new Captcha();
        BufferedImage image = cap.createRandomMathImage();

        //pubClass.setCache("imgcode_" + key, cap.captchaString, 5);
        session.setAttribute(key + "loginimgcode", cap.result);
        ImageIO.write(image, "JPEG", response.getOutputStream()); // 这样写需要tomcat存在temp文件夹，否则报错

//        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
//        encoder.encode(image);
    }

    @AuthTarget(AuthType.NONE)
    @GetMapping("/ts")
    public XJsonInfo ts(String type) {


        return XJsonInfo.success();
    }
}
